<?php

namespace app\admin\controller\home;

use app\common\controller\AdminController;
use app\common\webdav\auth\backend\Model;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;

/**
 * @ControllerAnnotation(title="home_user")
 */
class User extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\HomeUser();
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();

            if (empty($post['password'])) {
                $post['password'] = '123456';
            }

            $post['password_salt'] = uniqid();
            $password = $post['password'];
            $post['password'] = password($password, $post['password_salt']);

            $post['webdav_password'] = Model::buildDigestHash($post['username'], $password);

            $rule = [];
            $this->validate($post, $rule);
            try {
                $save = $this->model->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败:' . $e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');



        if ($this->request->isPost()) {
            $post = $this->request->post();

            if (isset($post['password'])) {
                if (empty($post['password'])) {
                    unset($post['password']);
                } else {
                    $password = $post['password'];
                    $post['password_salt'] = uniqid();

                    $post['password'] = password($password, $post['password_salt']);

                    $post['webdav_password'] = Model::buildDigestHash($post['username'], $password);
                }
            }

            $rule = [];
            $this->validate($post, $rule);
            try {
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }
}
